package marcis.jarina.hibernate;

import marcis.jarina.hibernate.dao.JavaClassDao;
import marcis.jarina.hibernate.entities.JavaClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ClassContinuousSaver implements ContinuousSaver<JavaClass> {

    private List<JavaClass> list = new ArrayList<JavaClass>();

    private static final int MAX = 500;

    @Autowired
    private JavaClassDao javaClassDao;

    @Override
    public void addEntity(JavaClass object) {
        list.add(object);
        if (isOverFlow(list)) {
            save();
            // to avoid high memory use
            list.clear();
        }
    }

    @Override
    public boolean isOverFlow(List<JavaClass> javaClasses) {
        return list.size() > MAX;
    }

    @Override
    public void save() {
        final JavaClass[] classArray = new JavaClass[list.size()];
        list.toArray(classArray);
        javaClassDao.save(classArray);
    }

    @Override
    public List<JavaClass> getList() {
        return list;
    }
}
